<template>
  <div>
    <el-table
      :data="datumRepayList"
      :height="dialogMaxheight"
      border
      cell-class-name="input-td"
      show-summary
      :summary-method="getSummaries"
      class="mb-3"
    >
      <el-table-column label="还款时间" prop="pay_time" align="center"></el-table-column>
      <el-table-column label="应还本金（元）" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.is_capital === '1' ? scope.row.capital : '-' }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="还本金额（元）"
                       align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.repay_amount"
                    type="number"
                    class="text-center"
                    v-if="scope.row.is_capital === '1'"
                    @blur="submit(scope.$index)"></el-input>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="应还利息（元）" align="center">
        <template slot-scope="scope">
          <span>
            {{
              scope.row.is_interest === '1' && isLastMonthAtQuarter(scope.row.pay_time)
                ? scope.row.interest
                : '-'
            }}
          </span>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="还息金额（元）"
                       align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.interest"
                    type="number"
                    class="text-center"
                    v-if="scope.row.is_interest === '1' && isLastMonthAtQuarter(scope.row.pay_time)"
                    @blur="submit(scope.$index)"></el-input>
        </template>
      </el-table-column> -->
      <el-table-column label="还款金额（元）" align="center">
        <template slot-scope="scope">
          <el-input
            v-model="scope.row.repay_amount"
            type="number"
            class="text-center"
            @blur="submit(scope.$index)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="是否正常" align="center">
        <template slot-scope="scope">
          <c-select
            v-model="scope.row.is_normal"
            class="w-100 text-center"
            :options="statusOptions"
            @change="onStatusChange(scope.row.is_normal, scope.$index)"
          ></c-select>
        </template>
      </el-table-column>
      <el-table-column label="备注（异常说明）" prop="remark" align="center">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remark" @blur="submit(scope.$index)"></el-input>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import datumRepayListMixin from '@/credit/mixin/mission/datumRepayList'
import entrustContractMixin from '@/credit/mixin/mission/entrustContract'

export default {
  components: {},
  mixins: [datumRepayListMixin, entrustContractMixin],
  props: {
    relatedId: String,
  },
  data: () => ({
    dialogMaxheight: 600,
    datumRepayList: [],

    id: '',
    statusOptions: {
      0: '待确认',
      1: '正常',
      2: '异常',
    },
  }),
  computed: {
    repayMonthType() {
      return +this.entrustContract.repay_method === 1
    },
    sums() {
      return this.getSums(this.datumRepayList)
    },
  },
  watch: {
    relatedId: {
      handler: function (val) {
        if (val) {
          this.id = val
          this.getData()
        }
      },
    },
  },
  created() {
    this.initRelated()
    this.initDialogMaxHeight()
  },
  mounted() {},
  methods: {
    initDialogMaxHeight() {
      const clientHeight =
        document.documentElement.clientHeight || document.body.clientHeight || window.innerHeight
      this.dialogMaxheight = clientHeight - 400
    },

    initRelated() {
      if (this.id) {
        return this.getData()
      }
      const storageData = JSON.parse(sessionStorage.getItem('customer_related_view')) || {}
      this.id = storageData.customer_related_id || this.$route.query.id || ''
      if (!this.id) return
      this.getData()
    },

    async getData() {
      await this.getEntrustContract(this.id)
      await this.getDatumRepayList(this.id)
    },

    onStatusChange(isNormal, index) {
      // this.datumRepayList[index].repay_amount = isNormal === '0' ? 0 : this.addRepayTotal(index)

      this.submit(index)
    },

    addRepayTotal(index) {
      let {
        capital,
        interest,
        is_interest: isInterest,
        is_capital: isCapital,
        pay_time: payTime,
      } = this.datumRepayList[index]

      capital = +isCapital === 1 ? +capital || 0 : 0
      interest = +isInterest === 1 && this.isLastMonthAtQuarter(payTime) ? +interest || 0 : 0
      return Math.round((capital + interest) * 100) / 100
    },

    async submit(index) {
      const [res, err] = await this.$utils.promise(this.updateDatumRepayListByIndex(index))
      if (err) {
        return this.$message.error(`修改还款计划失败（${(err && err.status) || ''}）`)
      } else {
        if (res) {
          this.$emit('success', res)
        }
      }
    },

    isLastMonthAtQuarter(payTime) {
      if (this.repayMonthType || !payTime) {
        return true
      }
      return (new Date(payTime).getMonth() + 1) % 3 === 0
    },

    getSums(list) {
      let [capitalSum, interestSum, repaySum] = [0, 0, 0]
      for (const item of list) {
        const capital = Number.parseFloat(item.capital)
        capitalSum += isNaN(capital) ? 0 : capital

        const interest = Number.parseFloat(item.interest)
        interestSum += isNaN(interest) ? 0 : interest
        const repay = Number.parseFloat(item.repay_amount)
        repaySum += isNaN(repay) ? 0 : repay
      }
      return [
        Math.round(capitalSum * 1e2) / 1e2,
        Math.round(interestSum * 1e2) / 1e2,
        Math.round(repaySum * 1e2) / 1e2,
      ]
    },

    getSummaries({ columns }) {
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        }
        if (index < 4) {
          sums[index] = this.sums[index - 1]
          return
        }
        sums[index] = ''
      })
      return sums
    },
  },
}
</script>

<style lang="scss" scoped>
.text-center /deep/ .el-input__inner {
  text-align: center;
}
.row-sum {
  background-color: $gray-100;
  padding-right: 20px;
  display: flex;
  flex-wrap: nowrap;
  .row-sum-td {
    flex: 1;
    padding: 0.5rem 0.25rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    text-align: center;
  }
}
</style>
